// Parses XML representations of Snap! objects
import { GeneratorFunction } from "./genfunction.js";
import { Scope, compileScript } from "./script-compiler.js";
import { List } from "./list.js";

function parseValue(xml, parentScope, refs, namedFunctions) {
    switch (xml.nodeName) {
        case "l": {
            return xml.textContent;
        }

        case "list": {
            // store my id
            refs.set(xml.attributes.id.nodeValue, arr);

            // parse each item of list
            var arr = [...xml.children].map(v => {
                if (v.nodeName !== "item") throw new Error("Expected <item> tag");
                return parseValue(v.firstChild, parentScope, refs, namedFunctions);
            });

            return new List(arr);
        }

        case "context": {
            // store this id
            refs.set(xml.attributes.id.nodeValue, arr);

            let scope = new Scope(parentScope);
            let script = null;

            for (let childNode of xml.children) {
                switch (childNode.nodeName) {
                    case "inputs": {

                    }

                    case "script": {
                        script = compileScript(childNode, scope, namedFunctions);
                    }

                    case "variables": {

                    }

                    case "receiver": {

                    }

                    case "origin": {

                    }
                }
            }

            console.group("Context compilation");
            console.log(script);
            console.groupEnd();

            let res = new GeneratorFunction("env", script);
            console.log(res);
            return res;
        }
    }
}

export { parseValue }